package core

import (
	"fmt"
	"gitee.com/feimos/dm/utils"
	"log"
	"os"
	"path/filepath"
)

func RemoveOneDocument(yamlContent *YamlContent, path string, writeYaml bool) error {

	root := yamlContent.Root
	ext := utils.GetExt(path)
	name := filepath.Base(path)

	if len(ext) == 0 || name == ext {
		ext = DmBizarreExtname
	}

	file := utils.JoinPath(root, ext, name)

	if !utils.Exists(file) {
		return fmt.Errorf("document path \"%v\" is not existed\n", file)
	}

	stat, err := os.Stat(file)

	if err != nil {
		return err
	}

	if stat.IsDir() {
		return fmt.Errorf("document path \"%v\" is found to be a folder, only file path is accepted\n", file)
	}

	fileInfo := CreateFileInfo(path, stat)
	isRemoved := yamlContent.RemoveItem(ext, fileInfo)

	if isRemoved {
		log.Printf("remove document \"%v\" in the config file successfully\n", name)
	} else {
		log.Printf("the document \"%v\" is not existed in the config file\n", name)
	}

	removePath := utils.JoinPath(root, ext, name)

	err = os.Remove(removePath)
	if err != nil {
		return err
	}

	log.Printf("remove document path \"%v\" successfully\n", path)

	if writeYaml {
		err = WriteYaml(yamlContent, true)
		if err != nil {
			return err
		}
	}

	return nil
}

func RemoveGlob(yamlContent *YamlContent, pattern string) error {
	matches, err := filepath.Glob(pattern)

	if err != nil {
		return err
	}

	for _, file := range matches {

		info, err := os.Stat(file)

		if err != nil {
			return err
		}

		if info.IsDir() || file == DmFile || file == DmIgnoreFile {
			continue
		}

		err = RemoveOneDocument(yamlContent, file, false)
		if err != nil {
			return err
		}
	}

	err = WriteYaml(yamlContent, true)
	if err != nil {
		return err
	}

	return nil
}
